package gbench.sandbox.misc;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;

/**
 * 
 * @author gbench
 *
 */
public class JunitSplitter {

    /**
     * 
     * @author gbench
     *
     * @param <T>
     */
    public class Splitter<T> {

        public Splitter(final List<T> list, int maxSize) {
            this.list = list;
            this.maxSize = maxSize;
        }

        public int size() {
            return this.list.size();
        }

        public Splitter<T> split() {
            if (this.list == null)
                return null;
            if (this.size() <= this.maxSize)
                return null;
            final int end = (this.list.size() >> 1);
            if (end < 1) return null;
            final var ll = this.list.subList(end, this.size());
            final var sp = new Splitter<>(ll, this.maxSize);
            this.list = this.list.subList(0, end);
            return sp;
        }

        public Stream<T> stream() {
            return this.list.stream();
        }

        public String toString() {
            return this.list.toString();
        }

        private List<T> list;
        private int maxSize;
    }

    @Test
    public void foo() {
        final var list = Stream.iterate(0, i -> i + 1).limit(10000).collect(Collectors.toList());
        final var spliter = new Splitter<Integer>(list, 100);
        final var stack = new Stack<Splitter<Integer>>();
        stack.push(spliter);
        final var spls = new LinkedHashMap<Number,Splitter<Integer>>();
        final var ai = new AtomicInteger(0);
        while (!stack.isEmpty()) {
            final var spl= stack.pop();
            final var _spl = spl.split();
            if (_spl != null) {
                stack.push(spl);
                stack.push(_spl);
            } else {
                spls.put(ai.getAndIncrement(),spl);
            }
        } // while
        
        spls.forEach((k,v) -> {
            System.out.println(k+"-"+v);
        });
    }

}
